package com.tank.netty.chat.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/5/29 0029
 * Time: 上午 11:37
 * To change this template use File | Settings | File Templates.
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    //保存链接对象
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //读写时间
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //当前channel
        Channel channel = ctx.channel();
        System.out.println(String.format("receive message:%s",msg));
        //循环在线channel组
        channelGroup.forEach(item -> {
            //非当前channel
            if(item != channel){
                item.writeAndFlush(String.format("[%s] 发送消息: %s \n",channel.remoteAddress(), msg));
            }else {
                channel.writeAndFlush(String.format("[%s] 发送消息: %s \n","自己", msg));
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();;
        ctx.close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    //    System.out.println(String.format("[服务端] :%s 上线 \n",ctx.channel().remoteAddress()));
        super.channelRegistered(ctx);
    }
    //链接添加
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();
        //广播
        channelGroup.writeAndFlush(String.format("[服务端] :%s 上线 \n",ctx.channel().remoteAddress()));
        //添加链接
        channelGroup.add(channel);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println((String.format("[服务端] :%s 上线 \n",ctx.channel().remoteAddress())));
    }

    //链接移除
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //广播
        channelGroup.writeAndFlush(String.format("客户端 :%s 离开 \n",ctx.channel().remoteAddress()));
        //自动调用
        //channelGroup.remove(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        channelGroup.writeAndFlush(String.format("客户端 :%s 下线 \n",ctx.channel().remoteAddress()));
    }
}
